package juc.reentryLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

import static juc.Sleeper.sleep;

//展示ReentryLock的可打断性
@Slf4j(topic = "c.ReentryLock02")
public class ReentryLock02 {
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        method1();
    }

    //可中断的锁获取
    public static void method1() {
        Thread t1 = new Thread(() -> {
            log.debug("启动。。。");
            try{
                //让线程可中断的获取锁
                lock.lockInterruptibly();
                //抛出打断异常后，则进行异常的处理
            }catch (InterruptedException e){
                e.printStackTrace();
                log.debug("等锁的过程中被打断");
                return;
            }
            //若没有上述的打断，则相当于t1获取了锁，执行下面代码
            try{
                log.debug("获得了锁");
            }finally {
                lock.unlock();
            }
        },"t1");

        lock.lock();
        log.debug("获得了锁");
        t1.start();
        try{
            sleep(1);
            t1.interrupt();
            log.debug("执行打断");
        }finally {
            lock.unlock();
        }
    }

    //不可中断的锁获取
    public static void method2() {
        Thread t1 = new Thread(() -> {
            log.debug("启动。。。");
            lock.lock();
            //若没有上述的打断，则相当于t1获取了锁，执行下面代码
            try{
                log.debug("获得了锁");
            }finally {
                lock.unlock();
            }
        },"t1");

        lock.lock();
        log.debug("获得了锁");
        t1.start();
        try{
            sleep(1);
            t1.interrupt();
            log.debug("执行打断");
        }finally {
            lock.unlock();
            log.debug("释放了锁");
        }
    }
}
